package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 * @ClassName TrackReceiver
 * @description: TODO
 * @date 2024年08月07日
 * @version: 1.0
 */
@Component
public class TrackReceiver {

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private RedisTemplate   redisTemplate;

    /**
     * 监听更新播放量
     * @param msg
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void trackStatUpdate(String msg, Message message, Channel channel){
        try {
            //  获取数据
            if(!StringUtils.isEmpty(msg)){
                //  进行数据类型专辑
                TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);
                if (redisTemplate.opsForValue().setIfAbsent(trackStatMqVo.getBusinessNo(),"1",1, TimeUnit.HOURS)) {
                    //  第一次消费
                    //  调用服务层方法.
                    try {
                        trackInfoService.trackStatUpdate(trackStatMqVo);
                    } catch (Exception e){
                        //  处理业务的时候出现了异常. 将key删除！
                        this.redisTemplate.delete(trackStatMqVo.getBusinessNo());
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


}
